package com.example.myweb.Controller.Auth;

import com.example.myweb.Common.ApiResponse;
import com.example.myweb.Domain.Entity.User;
import com.example.myweb.Dto.DraftSaveRequestDTO;
import com.example.myweb.Dto.DraftSummaryDTO;
import com.example.myweb.Service.Auth.DraftService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("/drafts")
public class DraftController {

    @Autowired
    private DraftService draftService;

    @PostMapping
    public ResponseEntity<ApiResponse<DraftSummaryDTO>> saveDraft(
            @Valid @RequestBody DraftSaveRequestDTO request,
            @AuthenticationPrincipal User currentUser) {
        DraftSummaryDTO savedDraft = draftService.saveDraft(request, currentUser);
        return ResponseEntity.ok(ApiResponse.success(savedDraft, "草稿已保存"));
    }

    @GetMapping("/me")
    public ResponseEntity<ApiResponse<List<DraftSummaryDTO>>> getMyDrafts(
            @AuthenticationPrincipal User currentUser) {
        List<DraftSummaryDTO> drafts = draftService.getUserDrafts(currentUser);
        return ResponseEntity.ok(ApiResponse.success(drafts, "获取草稿列表成功"));
    }

    @GetMapping("/{id}")
    public ResponseEntity<ApiResponse<Object>> getDraftContent(
            @PathVariable Long id,
            @AuthenticationPrincipal User currentUser) {
        Object content = draftService.getDraftContent(id, currentUser);
        return ResponseEntity.ok(ApiResponse.success(content, "获取草稿内容成功"));
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<ApiResponse<Void>> deleteDraft(
            @PathVariable Long id,
            @AuthenticationPrincipal User currentUser) {
        draftService.deleteDraft(id, currentUser);
        return ResponseEntity.ok(ApiResponse.success("草稿删除成功"));
    }
}